package com.meixiang.activity.account.myShopper;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lzy.okhttputils.model.HttpParams;
import com.meixiang.R;
import com.meixiang.activity.homes.shopping.CashierDeskActivity;
import com.meixiang.activity.homes.shopping.GoodsDetailActivity;
import com.meixiang.adapter.personalCenter.AllOrderItemAdapter;
import com.meixiang.entity.OrderResult;
import com.meixiang.entity.myOrder.MyOrderDetail;
import com.meixiang.entity.myOrder.OrderLogistics;
import com.meixiang.entity.myOrder.OrderUtils;
import com.meixiang.global.Config;
import com.meixiang.global.GlobalType;
import com.meixiang.http.HttpCallBack;
import com.meixiang.http.HttpUtils;
import com.meixiang.main.BaseActivity;
import com.meixiang.tool.Tool;
import com.meixiang.util.AbJsonUtil;
import com.meixiang.util.AbStrUtil;

import org.json.JSONObject;

import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.rong.imkit.RongIM;

/**
 * 订单详情
 * @author yinsujun  Created at 2016/5/9 15:27
 */
public class OrderDetailActivity extends BaseActivity {
    @Bind(R.id.order_detail_tv_order_no)
    TextView tvOrderNo;
    @Bind(R.id.order_detail_tv_order_status)
    TextView tvOrderStatus;
    @Bind(R.id.order_detail_tv_order_name_and_mobile)
    TextView tvOrderNameAndMobile;
    @Bind(R.id.order_detail_tv_order_address)
    TextView tvOrderAddress;
    @Bind(R.id.order_detail_tv_order_name)
    TextView tvOrderName;
    //    @Bind(R.id.order_detail_linear_order)
//    LinearLayout linearOrder;
    @Bind(R.id.order_detail_tv_disbursements)
    TextView tvDisbursements;
    @Bind(R.id.order_detail_tv_disbursements_money)
    TextView tvDisbursementsMoney;
    @Bind(R.id.order_detail_tv_confirm_time)
    TextView tvConfirmTime;
    @Bind(R.id.order_detail_tv_payment_time)
    TextView tvPaymentTime;
    @Bind(R.id.order_detail_tv_confirm)
    TextView tvConfirm;
    @Bind(R.id.order_detail_tv_delete)
    TextView tvDelete;
    @Bind(R.id.order_detail_relative_logistics)
    RelativeLayout relativeLogistics;
    @Bind(R.id.order_detail_linear_bottom)
    LinearLayout orderDetailLinearBottom;
    @Bind(R.id.order_detail_tv_total_money)
    TextView tvTotalMoney;
    @Bind(R.id.order_detail_tv_coupon)
    TextView tvCoupon;
    @Bind(R.id.order_detail_tv_shipping_fee)
    TextView tvShippingFee;
    @Bind(R.id.order_detail_recycler_view)
    RecyclerView recyclerView;
    @Bind(R.id.order_detail_relative_user_info)
    RelativeLayout relativeUserInfo;
    @Bind(R.id.order_detail_contact_service)
    LinearLayout linearContact;
    @Bind(R.id.order_detail_tv_logistics)
    TextView tvLogistics;
//    @Bind(R.id.order_detail_tv_disbursements)
//    TextView orderDetailTvDisbursements;
    @Bind(R.id.order_detail_relative_refund_info)
    RelativeLayout relativeRefundInfo;
    private String status, orderId,storeTel,refundId;
    private String orderTotalPrice="";
    private String isMainStore;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_order_detail);
        ButterKnife.bind(this);
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void initTitle() {
        setTitle("订单详情");
        status = getIntent().getStringExtra("status");
        orderId=getIntent().getStringExtra("orderId");
        refundId=getIntent().getStringExtra("refundId");
    }

    @Override
    protected void initView() {
        LinearLayoutManager linear = new LinearLayoutManager(context);
        linear.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(linear);
        if (!AbStrUtil.isEmpty(status)) {
            tvOrderStatus.setText(status);
            if (status.equals("待付款")) {
                relativeLogistics.setVisibility(View.GONE);
                relativeUserInfo.setVisibility(View.VISIBLE);
                relativeRefundInfo.setVisibility(View.GONE);

                tvOrderStatus.setTextColor(ContextCompat.getColor(context, R.color.order_red_color));
                tvDelete.setVisibility(View.VISIBLE);
                tvConfirm.setText("前去支付");
                tvDelete.setText("取消订单");
                tvPaymentTime.setVisibility(View.GONE);
                relativeLogistics.setVisibility(View.GONE);
            } else if (status.equals("待收货")||status.equals("待发货")) {
                tvOrderStatus.setTextColor(ContextCompat.getColor(context, R.color.order_status_color));
                tvDelete.setVisibility(View.GONE);
                tvConfirm.setText("确认收货");
                tvPaymentTime.setVisibility(View.VISIBLE);
            } else if (status.equals("待评价")) {
                tvOrderStatus.setTextColor(ContextCompat.getColor(context, R.color.order_green_color));
                tvDelete.setVisibility(View.VISIBLE);
                tvDelete.setText("删除订单");
                tvConfirm.setText("给它评价");
                tvPaymentTime.setVisibility(View.VISIBLE);
            } else if (status.equals("交易完成")) {
                relativeLogistics.setVisibility(View.VISIBLE);
                relativeUserInfo.setVisibility(View.VISIBLE);
                relativeRefundInfo.setVisibility(View.GONE);

                tvOrderStatus.setTextColor(ContextCompat.getColor(context, R.color.black_3));
                tvConfirm.setVisibility(View.GONE);
                tvDelete.setText("删除订单");
                tvDelete.setVisibility(View.VISIBLE);
                tvPaymentTime.setVisibility(View.VISIBLE);
            }else if(("退款/售后").equals(status)){
                relativeLogistics.setVisibility(View.GONE);
                relativeUserInfo.setVisibility(View.GONE);
                relativeRefundInfo.setVisibility(View.VISIBLE);

                tvOrderStatus.setTextColor(ContextCompat.getColor(context, R.color.black_3));
                tvConfirm.setVisibility(View.GONE);
                tvDelete.setText("删除订单");
                tvDelete.setVisibility(View.VISIBLE);
            }else if("已取消".equals(status)){
                relativeLogistics.setVisibility(View.GONE);
                relativeUserInfo.setVisibility(View.VISIBLE);
                relativeRefundInfo.setVisibility(View.GONE);
                tvOrderStatus.setTextColor(ContextCompat.getColor(context, R.color.black_3));
                tvConfirm.setVisibility(View.GONE);
                tvDelete.setText("删除订单");
                tvDelete.setVisibility(View.VISIBLE);
            }
        }


    }

    @Override
    protected void setData() {
        getData();
        getLogisticsData();
    }

    private void getLogisticsData(){
        String url= Config.CHECK_ORDER_LOGISTICS;
        HttpParams params=new HttpParams();
        if(!AbStrUtil.isEmpty(orderId)){
            params.put("orderId",orderId);
        }
        HttpUtils.post(url, params, new HttpCallBack(this) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                OrderLogistics orderLogistics= AbJsonUtil.fromJson(result.optJSONObject("order").toString(),OrderLogistics.class);
                if(orderLogistics!=null){
                    tvLogistics.setText(orderLogistics.getLogisticsFollow().get(orderLogistics.getLogisticsFollow().size()-1).getContext());
                }else{
                    tvLogistics.setText("暂无物流信息");
                }
            }

            @Override
            public void onError(String code, String message) {

            }
        });

    }

    private void getData() {
        String url = Config.GET_MY_ORDER_DETAIL;
        HttpParams params = new HttpParams();
//        if (("退款/售后").equals(status)) {
////            url=Config.GET_MY_ORDER_REFUND_DETAIL;
//            url = Config.SERVER_URL+"refund/refundDetial";
//            params.put("refundId",refundId);
////            params.put("orderGoodsId",orderGoodsId);
////            params.put("goodsId",goodsId);
//        }else
        if(!AbStrUtil.isEmpty(orderId)){
            params.put("orderId", orderId);
        }
        HttpUtils.post(url, params, new HttpCallBack(this,"加载中...") {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                MyOrderDetail orderDetail ;
//                if (("退款/售后").equals(status)) {
//                    SaleOrRefundDetail saleOrRefundDetail = AbJsonUtil.fromJson(result.toString(), SaleOrRefundDetail.class);
//
//                    orderDetail = new MyOrderDetail();
//                    /**
//                     private String orderId;
//                     private String orderSn;
//                     -- private String paymentState;
//                     private String orderState;
//                     private String orderAmount;
//                     private String orderTotalPrice;
//                     --private String trueName;
//                     --private String memberId;
//                     --private String telPhone;
//                     private String createTime;
//                     private String paymentTime;
//                     private String shippingFee;
//                     private String couponPrice;
//                     private String storeId;
//                     private String storeName;
//                     */
////                    orderDetail.setOrderId(saleOrRefundDetail.getGoodsId());
//                    orderDetail.setOrderSn(saleOrRefundDetail.getRefundSn());
//                    orderDetail.setOrderState(saleOrRefundDetail.getRefundState());
//                    orderDetail.setOrderAmount(saleOrRefundDetail.getRefundAmount());
//                    orderDetail.setOrderTotalPrice(saleOrRefundDetail.getGoodsPrice());
//                    orderDetail.setCreateTime(saleOrRefundDetail.getSellerTime());
////                    orderDetail.setPaymentTime(saleOrRefundDetail.getPaymentTime());
////                    orderDetail.setShippingFee(saleOrRefundDetail.getShippingFee());
////                    orderDetail.setCouponPrice(saleOrRefundDetail.getCouponPrice());
//                    orderDetail.setStoreId(saleOrRefundDetail.getStoreId());
//                    orderDetail.setStoreName(saleOrRefundDetail.getStoreName());
//
//                    /**
//                     private String recId;
//                     private String goodsId;
//                     private String goodsName;
//                     private String specId;
//                     private String goodsPrice;
//                     private String goodsImage;
//                     private List<String> specInfo;
//                     */
//
//                    List<MyOrderDetail.OrderGoodsListBean> goodsListBean = new ArrayList<MyOrderDetail.OrderGoodsListBean>();
//                    MyOrderDetail.OrderGoodsListBean goods = new MyOrderDetail.OrderGoodsListBean();
//                    goods.setRecId(saleOrRefundDetail.getRecId());
//                    goods.setGoodsId(saleOrRefundDetail.getGoodsId());
//                    goods.setGoodsName(saleOrRefundDetail.getGoodsName());
//                    goods.setGoodsNum(saleOrRefundDetail.getGoodsNum());
//                    goods.setSpecId(saleOrRefundDetail.getSpecId());
//                    goods.setGoodsPrice(saleOrRefundDetail.getGoodsPrice());
//                    goods.setGoodsImage(saleOrRefundDetail.getGoodsImage());
//                    goods.setSpecInfo(saleOrRefundDetail.getSpecInfo());
//                    goodsListBean.add(goods);
//                    orderDetail.setOrderGoodsList(goodsListBean);
//                } else {
                    orderDetail = AbJsonUtil.fromJson(result.toString(), MyOrderDetail.class);
//                }
//                refundId=orderDetail.getOrderGoodsList().get(0).getRefundState();
                isMainStore=orderDetail.getIsMainStore();
                orderTotalPrice=orderDetail.getOrderTotalPrice();
                if(!AbStrUtil.isEmpty(orderDetail.getStoreTel())){
                    storeTel=orderDetail.getStoreTel();
                }
                setDetailData(orderDetail);
            }

            @Override
            public void onError(String code, String message) {
                Tool.showTextToast(context, message);

            }
        });
    }

    private void setDetailData(final MyOrderDetail orderDetail) {
        AllOrderItemAdapter adapter;
        String orderStatus="";
        tvOrderNo.setText("订单号："+orderDetail.getOrderSn());
//        if (("退款/售后").equals(status)) {
//            orderStatus = OrderUtils.getRefund(orderDetail.getOrderGoodsList().get(0).getRefundState());
//            if(orderStatus.equals(3)){
//                tvConfirmTime.setText("退款时间：" + orderDetail.getCreateTime());
//            }
//            tvOrderStatus.setText(orderStatus);
//        } else {
//            orderStatus = OrderUtils.getOrderStatus(orderDetail.getOrderState(),orderDetail.getEvaluationStatus());
//            tvConfirmTime.setText("下单时间：" + orderDetail.getCreateTime());
//        }
        for(int i=0;i<orderDetail.getOrderGoodsList().size();i++){
//            if(!AbStrUtil.isEmpty(orderDetail.getOrderGoodsList().get(i).getRefundState())){
//                tvOrderStatus.setTextColor(ContextCompat.getColor(context,R.color.order_red_color));
//            }
            if(AbStrUtil.isEmpty(orderDetail.getOrderGoodsList().get(i).getRefundState())){
                orderStatus=OrderUtils.getOrderStatus(orderDetail.getOrderState(),orderDetail.getEvaluationStatus(),
                        orderDetail.getOrderGoodsList().get(i).getRefundState());
                break;
            }else{
                orderStatus=OrderUtils.getOrderStatus(orderDetail.getOrderState(),orderDetail.getEvaluationStatus(),
                        orderDetail.getOrderGoodsList().get(i).getRefundState());
            }
        }

        if (("退款/售后").equals(status)) {
            tvOrderStatus.setText(orderStatus);
        }else{
            tvOrderStatus.setText(OrderUtils.getOrderStatus(orderDetail.getOrderState(),orderDetail.getEvaluationStatus()));
        }

        tvConfirmTime.setText("下单时间：" + orderDetail.getCreateTime());
        //物流状态显示？？
        String trueName = orderDetail.getTrueName();
        if(AbStrUtil.isEmpty(trueName)){
            trueName="";
        }
        String telPhone = orderDetail.getTelPhone();
        if(AbStrUtil.isEmpty(telPhone)){
            telPhone="";
        }
        tvOrderNameAndMobile.setText("送至：" + trueName+ "  " +telPhone);
        String areaInfo = orderDetail.getAreaInfo();
        String address = orderDetail.getAddress();
        if(AbStrUtil.isEmpty(areaInfo)){
            areaInfo="";
        }
        if(AbStrUtil.isEmpty(address)){
            address="";
        }
        tvOrderAddress.setText(areaInfo+address);
        tvOrderName.setText(orderDetail.getStoreName());
        //列表
        adapter = new AllOrderItemAdapter(this, orderDetail);
        adapter.setType(1);
//        if(!AbStrUtil.isEmpty("status")&&status.contains("评价")){
//        }else{
//            adapter = new AllOrderItemAdapter(context, orderDetail, status,0);
//        }
        recyclerView.setAdapter(adapter);
        tvTotalMoney.setText(orderDetail.getOrderTotalPrice());
        tvCoupon.setText(orderDetail.getCouponPrice());
        tvShippingFee.setText(orderDetail.getShippingFee());
        tvDisbursementsMoney.setText(orderDetail.getOrderAmount());

        if(!AbStrUtil.isEmpty(orderDetail.getPaymentTime())){
            tvPaymentTime.setText("支付时间：" + orderDetail.getPaymentTime());
        }else{
//            tvPaymentTime.setVisibility(View.GONE);
            tvPaymentTime.setText("支付时间：");
        }

        adapter.setOnItemClickListener(new AllOrderItemAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int positions) {
                Intent intent=new Intent();
                intent.setClass(context, GoodsDetailActivity.class);
                if(!AbStrUtil.isEmpty(orderDetail.getOrderGoodsList().get(positions).getGoodsId())){
                    intent.putExtra(GoodsDetailActivity.GOODS_ID,orderDetail.getOrderGoodsList().get(positions).getGoodsId());
                    startActivity(intent);
                }
            }
        });
    }


    @Override
    public void onClick(View v) {

    }

    @OnClick({R.id.order_detail_relative_logistics, R.id.order_detail_tv_confirm, R.id.order_detail_tv_delete,R.id.order_detail_relative_refund_info
            ,R.id.order_detail_contact_service})
    void click(View view) {
        Intent intent = new Intent();
        if (view.equals(relativeLogistics)) {
            intent.setClass(context, OrderForCheckLogisticsActivity.class);
            intent.putExtra("orderId",orderId);
        } else if (view.equals(tvConfirm)) {
            String tvConfirmDetail = tvConfirm.getText().toString();
            if(!AbStrUtil.isEmpty(orderId)){
                intent.putExtra("orderId",orderId);
            }
            if (tvConfirmDetail.equals("给它评价")) {
                intent.setClass(context, OrderEvaluationActivity.class);
            }else if(tvConfirmDetail.equals("前去支付")){
                if(AbStrUtil.isEmpty(orderTotalPrice)){
                    Tool.showTextToast(context,"未获取支付金额");
                    return;
                }
                OrderResult mOrderResult=new OrderResult(orderTotalPrice,orderId);
                Log.e("TAG","测试传人数据mOrderResult"+mOrderResult.toString());
                Log.e("TAG","测试传人数据mOrderResult"+mOrderResult.getOrderId());
                intent.setClass(context,CashierDeskActivity.class);
                intent.putExtra(CashierDeskActivity.ORDER_RESULT,mOrderResult);
                intent.putExtra(CashierDeskActivity.PAYMENT_TYPE, CashierDeskActivity.ORDER_PAY);
                intent.putExtra(CashierDeskActivity.ORDER_TYPE,"SC");
                HashMap<String, Class> map = new HashMap<>();
                map.put(CashierDeskActivity.GOTO_ACTIVITY, MyAllOrderActivity.class);
                intent.putExtra(CashierDeskActivity.GOTO_ACTIVITY, map); // 支付成功之后跳转的activity
            } else if(tvConfirmDetail.equals("确认收货")){
                confirmOrder(orderId);
                return;
            }else {
                return;
            }
        } else if (view.equals(tvDelete)) {
            String leftTV = tvDelete.getText().toString();
            if("取消订单".equals(leftTV)){
                cancelOrder(orderId);
            }else if("删除订单".equals(leftTV)){
                deleteOrder(orderId);
            }
            return;
        }else if(view.equals(relativeRefundInfo)){
            intent.setClass(context,OrderRefundActivity.class);
            if(!AbStrUtil.isEmpty(refundId)){
                intent.putExtra("refundId",refundId);
            }else{
                Tool.showTextToast(context,"未获取订单ID");
                return;
            }
        }else if(view.equals(linearContact)){
            if (RongIM.getInstance() != null)
                if(!AbStrUtil.isEmpty(isMainStore)){
                    //1 是总店 0不是总店
                    if(isMainStore.equals("1")){
                        Tool.SelectCustomerService(context,true);
                    }else{
                        Tool.SelectCustomerService(context,false);
                    }
                }
            return;
        }
        startActivity(intent);
    }

    /**
     *确认订单
     *@author yinsujun
     */
    private void confirmOrder(final String orderId){
        String url=Config.ORDER_FOR_COMMIT_CONFIRM;
        HttpParams params=new HttpParams();
        params.put("orderId",orderId);
        HttpUtils.post(url, params, new HttpCallBack((Activity)context,"确认中...") {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                notifyOrderList();
                Tool.showTextToast(context,message);
            }

            @Override
            public void onError(String code, String message) {
                Tool.showTextToast(context,message);
            }
        });
    }
    /**
     *取消订单
     *@author yinsujun
     *created at 2016/5/25 17:13
     */
    private void cancelOrder(final String orderId){
        String url= Config.ORDER_FOR_CANCEL_ORDER;
        HttpParams params=new HttpParams();
        params.put("orderId",orderId);
        HttpUtils.post(url, params, new HttpCallBack((Activity)context,"取消中...") {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
//                context.getData();
                notifyOrderList();
                Tool.showTextToast(context,message);
            }

            @Override
            public void onError(String code, String message) {
                Tool.showTextToast(context,message);
            }
        });

    }
    /**
     *删除订单
     *@author yinsujun
     *created at 2016/5/25 17:13
     */
    private void deleteOrder(final String orderId){
        String url=Config.ORDER_FOR_DELETE_ORDER;
        HttpParams params=new HttpParams();
        params.put("orderId",orderId);
        HttpUtils.post(url, params, new HttpCallBack((Activity)context,"删除中...") {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                notifyOrderList();
                Tool.showTextToast(context,message);
            }

            @Override
            public void onError(String code, String message) {
                Tool.showTextToast(context,message);
            }
        });
    }
    private void notifyOrderList(){
        Intent intent=new Intent(GlobalType.ORDER_DETAIL_OPERATION);
//        intent.putExtra("orderId",orderId);
        sendBroadcast(intent);
        this.finish();
    }

}
